#-*- encoding: utf-8-*-
'''
Created on 2012-1-9

@author: Botao Wu
'''

from xml.etree.ElementTree import XMLParser

class TestTarget:                     # The target object of the parser
    
    def __init__(self):
        self.root = {}
        self.parent = {}
        self.parent_tag = None
        self.tag = None
        self.depth = 0
    
    def start(self, tag, attrib):   # Called for each opening tag.
        print 'tag: ', tag
        self.tag = tag
    
    def end(self, tag):              # Called for each closing tag.
        self.parent_tag = tag
        self.tag = None
        
    def data(self, data):
        self.root[self.tag] = data.strip()
        if self.tag == 'bank_no':
            print 'data: ', data.strip()
    
    def close(self):    # Called when all data has been parsed.
        return self.root


exampleXml = """<Message>
    <Message_Header>
        <bank_no>3132410666612410</bank_no>
        <channel_id>001</channel_id>
        <request_time>20100101121100</request_time>
        <response_time>20100101121100</response_time>
        <service_id>MB4002</service_id>
        <version_id>1.0</version_id>
        <response_code>00000000</response_code>
        <response_info>交易成功</response_info>
    </Message_Header>
    <Message_Body>
        <request>
        </request>
        <response>
            <tran_date>20100901</tran_date>
            <running_num>680001</running_num>
        </response>
    </Message_Body>
</Message>"""

exampleXml='''<a>
<b>1</b>
<b>2</b>
</a>'''


def parse(xml, parser):
    parser.feed(xml)
    return parser.close()


parser = XMLParser(target=TestTarget())
print parse(exampleXml, parser)






